<?php

/*
  +--------------------------------------------------------------------------
  |   Web: http://www.enbac.com
  |   Started date : 30/06/2008
  +---------------------------------------------------------------------------
  |   > Script written by Nova
  +---------------------------------------------------------------------------
 */

if (eregi(basename(__FILE__), $_SERVER['PHP_SELF'])) {
    print "<h1>Incorrect access</h1>You cannot access this file directly.";
    exit();
}

class ajax_item {

    function playme() {
        $code = AZLib::getParam('code');
        switch ($code) {
            case 'search_get_image':
                $this->search_get_image();
                break;
            case 'del_item':
                $this->fn_del_item();
                break;
            case 'item_same_category':
                $this->item_same_category();
                break;
            case 'search':
                $this->search();
                break;
            case 'item_history':
                $this->item_history();
                break;
            case 'remove_mem':
                $this->remove_mem();
                break;
            case 'add_group_filter':
                $this->add_group_filter();
                break;
            case 'add_filter':
                $this->add_filter();
                break;
            case 'rate':
                $this->rate_item();
                break;
            default:
                $this->home();
                break;
        }

        //$print->html = $skin->index();
        //$print->display();
    }

    function home() {
        die("Nothing to do...");
    }

    function search_get_image() {
        $item_id = AZLib::getParam('item_id');
        $page = Url::get('page', 0);
        $html = '';

        if ($item_id) {

            $sql_count_img = 'SELECT COUNT(*) AS total_img FROM item_image WHERE item_id = ' . $item_id;
            $sql_count_img_result = DB::query($sql_count_img);
            $total_img = mysql_fetch_assoc($sql_count_img_result);

            $total = $total_img['total_img'];
            $image_per_page = 10;
            $limit = $page * $image_per_page;
            $totalpage = ceil($total / $image_per_page);
            $i = 0;
            $sql_result = DB::query("SELECT title,position, img_url, img_server FROM item_image WHERE item_id=$item_id ORDER BY position ASC LIMIT $limit,$image_per_page");
            //$html .= '<table><tr><td width="30"><div id="pre_button_'.$page.'" style="display:none"><a href="javascript:void(0);" onclick="get_other_img('.$item_id.','.($page-1).')"><img src="style/images/pre_search.gif" vspace="4" hspace="4" title="Xem lại ảnh" alt="Xem lại ảnh"/></a></div></td><td><div>';

            $html .= '<div>';
            $html_script = '';
            while ($item_image = mysql_fetch_assoc($sql_result)) {
                if ($item_image['img_url']) {
                    $item_image['img_url'] = AZLib::getImageThumb($item_image['img_url'], 100, 100, 0, $item_image['img_server']);
                }
                if ($i == ($image_per_page / 2)) {
                    $html .= '<div style="clear:left"><span></span></div></div><div>';
                }
                $html .= '<div style="float:left;background:url(style/images/thumb_loading.gif) center 50% no-repeat; width:97px; height:97px; margin:0 10px 10px 0"><img src="' . $item_image['img_url'] . '" border="0" alt="' . $item_image['title'] . '" title="' . $item_image['title'] . '"></div>';

                $i++;
            }

            if ($i > ($image_per_page / 2)) {
                $html .= '<div style="clear:left"><span></span></div></div>';
            } else {
                $html .= '<div style="clear:left"><span></span></div>';
            }
            $page++;
            $html_script .= '<script>';
            $html_script .= 'document.getElementById("pre_button_' . $item_id . '_' . $page . '").style.display="inline";';
            if ($page > 1) {
                $html_script .= 'document.getElementById("next_button_' . $item_id . '_' . ($page - 1) . '").style.display="none";';
                $html_script .= 'document.getElementById("pre_button_' . $item_id . '_' . ($page - 1) . '").style.display="none";';
            }
            if ($page < $totalpage) {
                $html_script .= 'document.getElementById("next_button_' . $item_id . '_' . $page . '").style.display="inline";';
            }

            if ($page == $totalpage && $page > 1) {
                $html_script .= 'document.getElementById("next_button_' . $item_id . '_' . ($page - 1) . '").style.display="none";';
            }
            $html_script .= '</script>';
            $html .= '<div style="width:100%" align="right"><div id="pre_button_' . $item_id . '_' . $page . '" style="display:none"><a href="javascript:void(0);" onclick="clear_list_image(' . $item_id . ')"><img src="style/images/pre_search.gif" hspace="4" vspace="4" title="Thu gọn" alt="Thu gọn"/></a></div><div id="next_button_' . $item_id . '_' . $page . '" style="display:none"><a href="javascript:void(0);" onclick="get_other_img(' . $item_id . ',' . $page . ')"><img src="style/images/next_search.gif" hspace="4" vspace="4" title="Xem tiếp ảnh" alt="Xem tiếp ảnh" /></a></div></div>';

            echo ($html . $html_script);

            exit();
        } else {
            die("no_item");
        }
    }

    function fn_del_item() {

        $id = (int) Url::get('id', 0);

        if (!User::is_login()) {
            echo "not_login";
            exit();
        }

        if ($id > 0) {
            $item = Item::get_item($id);
            $item_memcache = $item;

            if (!User::have_permit(ADMIN_ITEM) && !User::have_cat_permit($item['category_id'])) {
                if ($item['user_id'] != User::id() || User::is_block()) {
                    echo "not_perm";
                    exit();
                }
            }
            $reason_del = AZLib::getParam("reason_del");
            Item::delete_item($id);
            DB::query("UPDATE user SET total_transaction = total_transaction-1 WHERE id=" . $item["user_id"]);
            if ((User::have_permit(ADMIN_ITEM) || User::have_cat_permit($item['category_id'])) && $reason_del) {

                $receiver_user = DB::select('user', 'id = ' . $item["user_id"]);

                $title_pm = 'Thông báo từ EnBac';

                $content_pm = 'Tin đăng \"' . $item['name'] . '\" của bạn đã bị xóa với lý do: ' . $reason_del . '
				
				Đề nghị bạn tham khảo [url=http://blog.enbac.com/2008/10/14/quy-che-dang-tin-tren-enbaccom.html]Quy định đăng tin[/url] hoặc [url=http://blog.enbac.com/2008/09/22/huong-dan-cac-chuc-nang-cua-enbac.html]hướng dẫn[/url] trên blog.enbac.com 
				
				Ban quản trị Én bạc.
				
				Vui lòng không trả lời tin nhắn này!';

                if (User::$current->data['signature'])
                    $content_pm .= '<br /><hr /><br />Mọi thắc mắc vui lòng liên hệ theo số ĐT: 04.39743410 - Số máy lẻ: ' . User::$current->data['signature'];

                AZLib::Send_pm(User::id(), User::user_name(), $receiver_user, $title_pm, $content_pm, true);

                $item_array = array(
                    'item_id' => $id,
                    'user_id' => User::id(),
                    'user_name' => User::user_name(),
                    'lock_time' => TIME_NOW,
                    'type' => 1,
                    'reason_lock' => $reason_del
                );
                DB::insert('item_lock', $item_array);
            }
            echo "success";
            exit();
        }
        else {
            echo "unsuccess";
            exit();
        }
    }

    function item_same_category() {
        global $display;
        /*$p_item_same = (int) Url::get('p_item_same', 1);
        if ($p_item_same == 0 || $p_item_same == 1) {
            if (StaticCache::notExistCache('item_same_cat_' . CGlobal::$curCategory . '_' . CGlobal::$curCity, 60)) {
                StaticCache::startCache();
                $this->item_same_category_form();
                StaticCache::endCache();
            }
        } else */
        {
            $this->item_same_category_form();
        }
    }

    function item_same_category_form() {
        global $display;
        AZLib::getProvinces();
        AZLib::getCats();
		
        $item_id = (int)Url::get('item_id');
		
        $sql = 'SELECT id, name, list_brief, offer, modify_time, sku, read_count, category_id, currency_id, price, price_out, img_url, img_server FROM item WHERE';
        $where = " id!=$item_id";

        if (CGlobal::$curCategory) 
        {
            $where .= ( $where != '' ? " AND " : "") . " category_id = " . CGlobal::$curCategory;
        }
        $where .= ( $where != '' ? " AND " : "") . " status=1";

        if (CGlobal::$curCity) {
           // $where = " province_id = " . CGlobal::$curCity . ($where != '' ? " AND " : "") . $where;//ngannv comment vì k có trường province id trong bảng item
        }
        $sql .= "$where ORDER BY item_order ASC";

        $divID 	= 'item_same_cat';
        $code 	= 'item_same_cat';
        
        $url_path = WEB_DIR . "ajax.php?act=item&code=item_same_category&category_id=" . CGlobal::$curCategory."&item_id=$item_id";

        $limit 			= '';
        $item_per_page 	= 3;
        $i 				= 1;
        
        $pagging 	= AZPagging::AjaxPagingNext($limit, $item_per_page, true, 'p_item_same', $url_path, $divID);
        $sql 	   .=$limit;

        $items 	 	= array();
        $re 		= DB::query($sql);

        if($re)
        {
            while ($item = mysql_fetch_assoc($re))
            {
                

                if ($i <= $item_per_page) 
               	{
               		if(isset(CGlobal::$allCategories[$item['category_id']])){
						$item['href'] = WEB_DIR.CGlobal::$allCategories[$item['category_id']]['nice_name']."/p{$item['id']}/".AZLib::safe_title($item['name']).".html";
					}
					else{	
						$item['href'] = WEB_DIR."p{$item['id']}/".AZLib::safe_title($item['name']).".html";
					}
			
					$item['modify_time'] = date('H:i | d.m.y',$item['modify_time']);
					
					$item['price_num'] = (int)$item['price'];
					
					if($item['price']){
						$item['price'] = number_format($item['price'],0,',','.');
					}
					else{
						$item['price'] = '';
					}
					
					
					$item['price_title'] = 'Giá bán';	
					
					if($item['price_out']>0)
					{
						$item['price_out'] = number_format($item['price_out'],0,',','.').($item['currency_id']==' '?' '.CGlobal::$currency[$item['currency_id']]:'');
					}
					else{
						$item['price_out'] = '0';
					}
					
					//$item['price'] 			= AZLib::convertCurrency($item['price'],			$item['currency_id']);
					//$item['price_out'] 		= AZLib::convertCurrency($item['price_out'],		$item['currency_id']);
					
					$item['name'] 		= AZLib::filter_title($item['name']);
					
					if ($item['img_url']){
						$item['img_thumb_wl'] 		= AZLib::getImageThumb($item['img_url'],180,0,1,$item['img_server']);
					}
					else{
						$item['img_url'] 			=  '';
					}
					
					if(!CGlobal::$curLevel2Cat){
						if(isset(CGlobal::$allCategories[$item['category_id']])){
							$item['cat_name'] = CGlobal::$allCategories[$item['category_id']]['name'];
						}
						else{
							$item['cat_name'] = "ID: {$item['category_id']}";
						}
					}
					
					$items[$item['id']] = $item;
                   /* 
                   $value['price'] = AZLib::convertCurrency($value['price'], $value['currency_id']);
                  $value['currency_id'] = 1;
                 
                   if (isset(CGlobal::$allCategories[$value['category_id']]))
                    {
                        $value['href'] = WEB_DIR . AZRewrite::formatUrl('?page=item_detail&id=' . $value['id'] . '&ebname=' . AZLib::safe_title($value['name']) . '&nice_name=' . CGlobal::$allCategories[$value['category_id']]['nice_name']);
                    } else {
                        $value['href'] = WEB_DIR . AZRewrite::formatUrl('?page=item_detail&id=' . $value['id'] . '&ebname=' . AZLib::safe_title($value['name']));
                    }

                    $value['item_time'] = date('h:i | d.m', $value['modify_time']);


                    $value['price_name'] = 'Giá bán';
                    $value['item_type'] = 'Giao dịch bán';

                    $value['name'] = strip_tags(AZLib::filter_title($value['name']));

                    if ($value['price'] && $value['price'] > 0) {
                        $value['price'] = number_format($value['price'], 0, ',', '.');
                        $value['currency_id'] = CGlobal::$currency[$value['currency_id']];
                    } else {
                        $value['price'] = 'Liên hệ';
                        $value['currency_id'] = '';
                    }

                    if ($value['img_url']) {
                        $value['img_url'] = AZLib::getImageThumb($value['img_url'], 80, 80, 0, $value['img_server']);
                    } else {
                        $value['img_url'] = 'style/images/no-images-69x53.jpg';
                    }

                    $items[$value['id']] = $value;
                	*/
                }
                
                $i++;
            }
        }

        if ($i <= $item_per_page)
        {
            $pagging = AZPagging::AjaxPagingNext($limit, $item_per_page, false, 'p_item_same', $url_path, $divID);
        }

        $display->add('pagging', $pagging);
        $display->add('items', $items);
        
       $display->add('admin_item',User::have_permit(ADMIN_ITEM));

        if ($items) {
            if (Url::get('code') != $code)
                echo '<div id="' . $divID . '">';
            else
                echo "<div>";

            $display->output('ItemSameCategory', false, 'ItemSameCategory');

            echo "</div>";
        }
    }

    function search() {
        global $display;
        $catid = (int) Url::get('catid', 0);
        $total = (int) Url::get('total', 0);
        $page = (int) Url::get('page', 0);
        $tt = (int) Url::get('tt', 0);
        $keywords = Url::get('keywords');

        require ( "./includes/sphinxapi.class.php" );

        AZLib::getCats();

        foreach (CGlobal::$allCategories as $value) {

            if ($value['parent_id'] == 0) {
                $cat_list[$value['id']] = $value['brief_name'];
            }
        }
        $category = $this->getCategory($keywords);

        foreach ($category as $row) {
            $row['brief_name'] = (isset($cat_list[$row['level_1_catid']]) && $cat_list[$row['level_1_catid']]) ? $cat_list[$row['level_1_catid']] : "Khác";
            $listCat[$row['level_1_catid']] = array("level_1_catid" => $row["level_1_catid"], "brief_name" => $row['brief_name'], "count_ad" => $row['@count']);
        }

        $catActive = '';
        $total_cat = 0;
        if ($listCat) {
            $catActive = $listCat[$catid]['brief_name'];
            $total_cat = count($listCat);
        }

        $i = 0;
        $allrecord = 0;
        $otherCat = '';
        $cat_content = "";
        foreach ($listCat as $cat) {
            $allrecord = $allrecord + $cat['count_ad'];
        }
        $display->add("cat_content", $cat_content);
        $display->add("CatActiveId", $catid);
        $display->add("catActive", $catActive);
        $display->add("listCat", $listCat);
        $display->add("allrecord", $allrecord);
        $display->add("total_cat", $total_cat);

        $pager = new Pager();

        $limit = SEARCH_LIMIT;

        $pager->type = "search";
        $pager->catid = $catid;
        $pager->total = $total;
        $pager->limit = $limit;

        $pager->page_param = 'page';
        $pager->page = $page;



        $offset = $pager->get_offset();
        $limit_from = $pager->limit_from();
        $limit_to = $pager->limit_to();

        //Sphinx search by Nova
        $q = $keywords;
        //$mode = SPH_MATCH_ALL;
        $mode = SPH_MATCH_EXTENDED2;
        //Init config
        $host = SPHINX_SERVER;
        $port = SPHINX_PORT;
        $index = 'enbac';
        $filtervals = array();
        //$ranker = SPH_RANK_PROXIMITY_BM25;
        $ranker = SPH_RANK_WORDCOUNT;

        $cl = new SphinxClient ();
        $cl->SetServer($host, $port);
        $cl->SetConnectTimeout(1);
        $cl->SetWeights(array(100, 1));
        $cl->SetMatchMode($mode);

        $cl->SetFilter('level_1_catid', array($catid));
        $cl->SetFilter('status', array('1'));
        $cl->SetFieldWeights(array('user_name'=>10000,'name'=>1000,'description'=>1));
        //$cl->SetSortMode( SPH_SORT_EXTENDED, 'up_time DESC' );
        //$cl->SetSortMode( SPH_SORT_RELEVANCE);//Sort theo kq chính xác nhất
        //$cl->SetSortMode ( SPH_SORT_EXPR, "@weight + ( user_karma + ln(pageviews) )*0.1");
        $cl->SetSortMode(SPH_SORT_EXPR, "@weight"); //Sort theo trọng số

        $cl->SetLimits($offset, $limit, 10000);
        $cl->SetRankingMode($ranker);
        $cl->SetArrayResult(true);

        $res = $cl->Query($q, $index);

        if ($res && isset($res["matches"])) {
            if (is_array($res["matches"])) {
                foreach ($res["matches"] as $results) {
                    $list_item_id[] = $results['id'];
                }
            }
            $comma_separated = join(",", $list_item_id);
        }

        if ($total) {
            if ($limit_to > $total) {
                $limit_to = $total;
            }

            $comma_separated = join(",", $list_item_id);

            if ($comma_separated) {
                //$sql = "SELECT id,name,up_time,price,user_id,user_name, level_1_catid,category_id,description,img_url, img_server FROM item WHERE id IN ($comma_separated) AND status=1 ORDER BY up_time DESC";
                $sql = "SELECT id,name,up_time,price,user_id,user_name, level_1_catid,category_id,description,img_url, img_server FROM item WHERE id IN ($comma_separated) AND status=1 ORDER BY find_in_set(id,'$comma_separated')";
                $search_result = DB::query($sql);

                $pager->total = $total;
                $paging = $pager->page_link();
            }
        }
        $item_array = array();
        if ($search_result) {

            AZLib::getCats();

            $highlight='';
            if($keywords){
                    $highlight=$str_search = str_replace( array('+','/','|','-','*') , "", $keywords );
                    $highlight = AZLib::trimSpace($highlight);

                    $highlight = str_replace( "'" , '', $highlight );
                    $highlight = str_replace( "&#39;" , '', $highlight );
                    $highlight = str_replace( "&quot;" , '', $highlight );
            }

            $highlight1 = '';
            if($highlight){
                    $arr=explode(' ',$highlight);

                    if($arr){
                            $highlight="";
                            foreach($arr as $word){
                                $highlight=($highlight?$highlight.', ':'')."'$word'";
                                $highlight1=($highlight1?$highlight1.',':'').$word;
                            }
                    }
            }

            while ($item = mysql_fetch_assoc($search_result)) {

                $item['profile_url'] = WEB_DIR . $item['user_name'];
                //$item['name'] = AZLib::subString(strip_tags(AZLib::filter_title($item['name'])), 0, 115, true);
                $item['name_hl'] = AZLib::HighLightKeyword(strip_tags(AZLib::filter_title($item['name'])),$highlight1);
                $item_time = TIME_NOW - $item['up_time'];
                //neu nho hon 1h thi tinh ra phut
                if ($item_time < 3600) {
                    $item['item_time'] = floor($item_time / 60) . " phút trước đây";
                }
                //neu nho hon 1 ngay thi tinh ra gio`
                elseif ($item_time < 86400) {
                    $item['item_time'] = floor($item_time / 3600) . " giờ trước đây";
                } else {
                    $item['item_time'] = date('\n\gà\y j \t\há\n\g n', $item['up_time']);
                }

                //$item['description'] = String::display_sort_title(AZLib::delDoubleSpace(AZLib::trimSpace(strip_tags(AZLib::post_db_parse_html($item['description'])))), 35);
                $item['description'] = AZLib::HighLightKeyword(AZLib::delDoubleSpace(AZLib::trimSpace(strip_tags( AZLib::post_db_parse_html(preg_replace('/\[[0-9]{1,3}\]/', '', $item['description']))))),$highlight1,35,"background:yellow;font-size:14px;font-weight:bold;color:blue;");

                $ebname = AZLib::safe_title($item['name']);

                $ebname_tmp = substr(AZLib::safe_title($item['name']), 0, 20);

                if (isset(CGlobal::$allCategories[$item['category_id']])) {
                    $item['item_url'] = WEB_DIR . AZRewrite::formatUrl('?page=item_detail&id=' . $item['id'] . '&ebname=' . $ebname . '&nice_name=' . CGlobal::$allCategories[$item['category_id']]['nice_name']);
                    $item['item_url_tmp'] = WEB_ROOT . CGlobal::$allCategories[$item['category_id']]['nice_name'] . '/p' . $item['id'] . '/' . $ebname_tmp . '...';
                } else {
                    $item['item_url'] = WEB_DIR . AZRewrite::formatUrl('?page=item_detail&id=' . $item['id'] . '&ebname=' . $ebname);
                    $item['item_url_tmp'] = WEB_ROOT . 'p' . $item['id'] . '/' . $ebname_tmp . '...';
                }

                if ($item['img_url']) {
                    $item['img_url'] = AZLib::getImageThumb($item['img_url'], 110, 0, 1, $item['img_server']);
                }

                $item['price'] = number_format($item['price'], 0, ',', '.');

                $item_array[] = $item;
            }
        }

        $display->add('total_item_cat', $total);
        $display->add('name_item_cat', $catActive);
        $display->add('paging', $paging);
        $display->add('keywords', $keywords);
        $display->add('items', $item_array);
        $display->output('sphinx_search_ajax', false, 'sphinx_search');
    }

    function item_history() {
        $itemids = Url::get('itemids');

        $item_history = array();

        if ($itemids) {
            $re = DB::query("SELECT id, name, price, currency_id, img_url, img_server, status, state  FROM item WHERE id IN($itemids) ORDER BY find_in_set(id, '$itemids')");

            if ($re) {
                while ($fitem = mysql_fetch_assoc($re)) {
                    if ($fitem['status'] == 1 && $fitem['state'] == 0) {
                        $item['item_id'] = $fitem['id'];
                        $item['item_url'] = "p" . $fitem['id'] . "/" . AZLib::safe_title($fitem['name']) . ".html";
                        $item['item_title'] = ucfirst(AZLib::remove_4_js($fitem['name']));

                        // $item['price']  		= $fitem['price']?number_format($fitem['price'],0,',','.'):'Liên hệ';
                        $item['price'] = $fitem['price'] ? number_format(AZLib::convertCurrency($fitem['price'], $fitem['currency_id']), 0, ',', '.') : 'Liên hệ';

                        //$item['item_image']  	= ($fitem['img_url']) ? AZLib::getImageThumbIn($fitem['img_url'],150,120,$fitem['img_server']) : '';
                        $item['item_image'] = ($fitem['img_url']) ? AZLib::getImageThumb($fitem['img_url'], 120, 105, 0, $fitem['img_server']) : '';

                        $item_history[] = $item;
                    }
                }
            }
        }

        echo json_encode($item_history);
    }

    function getCategory($keywords) {
        $q = $keywords;

        $mode = SPH_MATCH_EXTENDED;

        $item = array();
        $comma_separated = "";
        //Init config
        $host = SPHINX_SERVER;
        $port = SPHINX_PORT;
        $index = '*';

        $ranker = SPH_RANK_PROXIMITY_BM25;

        $cl = new SphinxClient ();

        $cl->SetServer($host, $port);
        $cl->SetConnectTimeout(1);
        $cl->SetWeights(array(100, 1));
        $cl->SetMatchMode($mode);
        $cl->SetRankingMode($ranker);
        $cl->SetArrayResult(true);
        $cl->SetFilter('status', array('1'));
        $cl->SetGroupBy("level_1_catid", SPH_GROUPBY_ATTR, "@count DESC");

        $res = $cl->Query($q, $index);
        $arr = array();
        if ($res && isset($res["matches"])) {
            if (is_array($res["matches"])) {
                foreach ($res["matches"] as $results) {
                    $arr[] = $results["attrs"];
                }
            }
        }
        return $arr;
    }

    function remove_mem() {
        if (!User::is_login()) {
            echo "not_login";
            exit();
        }

        if (User::is_block()) {
            echo "no_permission";
            exit();
        }

        if (User::have_permit(ADMIN_ITEM))
        {
            $item_id = AZLib::getParam('item_id');
            
            $id = "item:$item_id";
            AZMemcache::do_remove($id);
            
            echo "success";
        } else {
            die("no_permission");
        }
    }
 	
    function add_group_filter()
    {
        $data = array('msg'=>'');
		
		if(User::is_login())
		{
			if(User::have_permit(ADMIN_ITEM))
			{
				$catid 		= (int)Url::get("catid");
				$gf_name 	= trim(Url::get("gf_name"));
				
				if($catid && isset(CGlobal::$allCategories[$catid]))//Đã có giỏ hàng
				{
					if($gf_name!='')
					{
						$gf_pos	=	1 + (int)DB::fetch("SELECT max(pos) AS max_pos FROM filter_group",'max_pos',0);
					
						$gfilter_group =	array(	
													'name'		=>$gf_name,
													'catids'		=>$catid,
													'pos'		=>$gf_pos
												 ); 
		
						$id = DB::insert('filter_group', $gfilter_group);
						
						AZLib::getFilters(1);
					
						$data['id'] 		= $id;
						echo json_encode($data);
						exit;
					}
					else
					{
						$data = array('msg'=>'Bạn chưa nhập tên nhóm thuộc tính!');
						echo json_encode($data);
						exit;		
					}
				}
				else
				{
					$data = array('msg'=>'Danh mục không tồn tại!');
					echo json_encode($data);
					exit;		
				}
			}
		}
		else 
		{
			$data['msg'] = 'not_login';
			echo json_encode($data);
			exit;
		}
		
		$data['msg'] = 'no_perm';
		echo json_encode($data);
		exit;
    }

    function add_filter()
    {
        $data = array('msg'=>'');
		
		if(User::is_login())
		{
			if(User::have_permit(ADMIN_ITEM))
			{
				AZLib::getFilters();
				
				$fgid 		= (int)Url::get("fgid");
				$f_name 	= trim(Url::get("f_name"));
				
				if($fgid && isset(CGlobal::$all_gfilters[$fgid]))//Đã có giỏ hàng
				{
					if($f_name!='')
					{
						$f_pos	=	1 + (int)DB::fetch("SELECT max(pos) AS max_pos FROM filter WHERE fgid=$fgid",'max_pos',0);
					
						$filter =	array(	
													'name'	=>$f_name,
													'fgid'	=>$fgid,
													'pos'	=>$f_pos
												 ); 
		
						$id = DB::insert('filter', $filter);
						
						AZLib::getFilters(1);
					
						$data['id'] 		= $id;
						echo json_encode($data);
						exit;
					}
					else
					{
						$data = array('msg'=>'Bạn chưa nhập tên cho thuộc tính!');
						echo json_encode($data);
						exit;		
					}
				}
				else
				{
					$data = array('msg'=>'Nhóm thuộc tính không tồn tại!');
					echo json_encode($data);
					exit;		
				}
			}
		}
		else 
		{
			$data['msg'] = 'not_login';
			echo json_encode($data);
			exit;
		}
		
		$data['msg'] = 'no_perm';
		echo json_encode($data);
		exit;
    }
    
    function rate_item()
    {
		if(User::is_login())
		{
			$item_id	=	Url::get('id',0);
			$num_stars	=	Url::get('num_stars',0);
			$type		=	Url::get('type',0);
			$user_id	=	User::id();
			
			if($type!=0 && $type!=1 && $type!=2)
			$type=0;
			
			if($item_id && $user_id)
			{
				$item	=	Item::get_item($item_id);
				
				if($item && $item['status'] == 1 && (User::have_permit(ADMIN_ITEM) || !DB::select("item_rating","type="+$type+" AND user_id=".$user_id." AND item_id=".$item_id)))
				{
					$rank=(($item['rank']*$item['rate_num']+$num_stars)/($item['rate_num']+1));
					
					if($type==0)
					{
						$f_rank=(($item['f_rank']*$item['f_rate_num']+$num_stars)/($item['f_rate_num']+1));
						$update_sql="f_rank= $f_rank, f_rate_num=f_rate_num+1";
					}
					elseif($type==1)
					{
						$d_rank=(($item['d_rank']*$item['d_rate_num']+$num_stars)/($item['d_rate_num']+1));
						$update_sql="d_rank= '$d_rank', d_rate_num=d_rate_num+1";
					}
					else
					{
						$u_rank=(($item['u_rank']*$item['u_rate_num']+$num_stars)/($item['u_rate_num']+1));
						$update_sql="u_rank= '$u_rank', u_rate_num=u_rate_num+1";
					}
					
					if(!User::have_permit(ADMIN_ITEM))
					DB::insert("item_rating",array('user_id'=>$user_id,'item_id'=>$item_id,'rank'=>$num_stars,'type'=>$type,'time'=>TIME_NOW));		
					
					DB::query("UPDATE item SET `rank`= '".$rank."', `rate_num`=rate_num+1, ".$update_sql." WHERE id=".$item_id);
					
					Item::get_item($item_id,1);
				}
				
				exit;
			}
	    }
	    else{
	    	echo 'not_login';
			exit;
	    }
	    
	    echo 'no_perm';
		exit;
    }
}
?>